package com.yxq.mdt.app.modules.bottomsheet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.orhanobut.hawk.Hawk;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.personal.bean.MainPersonTokenBean;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.personal.model.MainPersonalModel;
import com.yxq.mdt.app.modules.personal.ui.activity.RechargeActivity;
import com.yxq.mdt.app.modules.socialcontact.bean.GiftResultBean;
import com.yxq.mdt.app.modules.socialcontact.bean.GivePresentBean;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.widgets.pagemenulibrary.IndicatorView;
import com.yxq.mdt.app.widgets.pagemenulibrary.PageMenuLayout;
import com.yxq.mdt.app.widgets.pagemenulibrary.holder.AbstractHolder;
import com.yxq.mdt.app.widgets.pagemenulibrary.holder.PageMenuViewHolderCreator;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author L
 * @time 2019-10-30
 * @describe 送礼弹窗
 */
public class GiveListBottomSheetDialogFragment extends BottomSheetDialogFragment {
    Unbinder unbinder;
    List<GivePresentBean.DataBean.ListBean> givePresentBeans;
    @BindView(R.id.pagemenu)
    PageMenuLayout<GivePresentBean.DataBean.ListBean> mPageMenuLayout;
    @BindView(R.id.main_home_entrance_indicator)
    IndicatorView entranceIndicatorView;
    @BindView(R.id.give_lint)
    LinearLayout giveLint;
    @BindView(R.id.Recharge)
    LinearLayout Recharge;
    String name;
    String userId;
    int positionSelected = -1;
    MyPersonalBean myPersonalBean;
    @BindView(R.id.give_item_money)
    TextView giveItemMoney;
    MainPersonTokenBean mainPersonTokenBean;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置背景透明，才能显示出layout中诸如圆角的布局，否则会有白色底（框）
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme);

    }

    public GiveListBottomSheetDialogFragment(List<GivePresentBean.DataBean.ListBean> givePresentBean, String userId, String name) {
        this.givePresentBeans = givePresentBean;
        this.name = name;
        this.userId = userId;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.give_list_bottom_sheet_fragment_dialog, container, false);
        unbinder = ButterKnife.bind(this, view);
        initViews();
        return view;
    }

    private void initViews() {
        mainPersonTokenBean = Hawk.get(SPKey.SP_KEY_USER_INFO_TOKEN);
        myPersonalBean = Hawk.get(SPKey.SP_KEY_USER_MY_INFO);
        giveItemMoney.setText(myPersonalBean.getMoney() + "");
        mPageMenuLayout.setPageDatas(givePresentBeans, new PageMenuViewHolderCreator() {
            @Override
            public AbstractHolder createHolder(View itemView) {

                return new AbstractHolder<GivePresentBean.DataBean.ListBean>(itemView) {
                    TextView entranceNameTextView;
                    ImageView entranceIconImageView;
                    TextView entranceNameMoney;
                    LinearLayout linearLayout;

                    @Override
                    protected void initView(View itemView) {
                        entranceIconImageView = itemView.findViewById(R.id.give_item_img);
                        entranceNameTextView = itemView.findViewById(R.id.give_item_tv);
                        entranceNameMoney = itemView.findViewById(R.id.give_item_money);
                        linearLayout = itemView.findViewById(R.id.give_item_lint);
                    }

                    @Override
                    public void bindView(RecyclerView.ViewHolder holder, final GivePresentBean.DataBean.ListBean data, int pos) {
                        entranceNameTextView.setText(data.getPresentName());
                        GlideHelper.setLoadImage(getActivity(), data.getPresentUrl(), 0, entranceIconImageView);
                        entranceNameMoney.setText(data.getPrice() + "蜜豆");
                        //选中
                        linearLayout.setOnClickListener(view -> {
                            positionSelected = pos;
                            initViews();
                        });
                        if (positionSelected == pos) {
                            linearLayout.setBackgroundColor(getResources().getColor(R.color.give));
                        } else {
                            linearLayout.setBackgroundColor(getResources().getColor(R.color.white));
                        }
                    }

                };
            }

            @Override
            public int getLayoutId() {
                return R.layout.give_item_list;
            }
        });
        entranceIndicatorView.setIndicatorCount(mPageMenuLayout.getPageCount());
        mPageMenuLayout.setOnPageListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                entranceIndicatorView.setCurrentIndicator(position);
            }
        });
        mPageMenuLayout.setCurrentPage((positionSelected / 8));
        //赠送
        giveLint.setOnClickListener(view -> {
            if (positionSelected == -1) {
                ToastUtils.showShort("请选择礼物");
            } else {
                sendGift(givePresentBeans.get(positionSelected).getId(), givePresentBeans.get(positionSelected).getPresentUrl(), givePresentBeans.get(positionSelected).getPrice(), givePresentBeans.get(positionSelected).getPresentName());
            }

        });
        //充值
        Recharge.setOnClickListener(view -> {
            Intent it = new Intent(getActivity(), RechargeActivity.class);
            getActivity().startActivity(it);
        });

    }

    private void sendGift(String giftId, String img, double money, String PresentName) {
        //送礼物接口
        if (giveListBottomSheetDialogFragmentInterface != null) {
            giveListBottomSheetDialogFragmentInterface.giftShowDialog(true);
        }
        MainPersonalModel.getPersonalDate(Constant.getLbsUserToken(), new ApiModel.CommonCallback<MyPersonalBean>() {
            @Override
            public void onSuccess(MyPersonalBean myPersonalBean) {
                if (myPersonalBean.getMoney() > 0f) {
                    MainSocialContactModel.addOrUpdateGive(userId, giftId, new ApiModel.CommonCallback<GiftResultBean>() {
                        @Override
                        public void onSuccess(GiftResultBean giftResultBean) {
                            if (giveListBottomSheetDialogFragmentInterface != null) {
                                giveListBottomSheetDialogFragmentInterface.giftShowDialog(false);
                            }
                            if (giftResultBean != null && "500".equals(giftResultBean.getStatus())) {
                                CostumerDialog dialog = new CostumerDialog.Builder(getActivity(), R.style.custom_dialog_no_match)
                                        .setContentView(R.layout.dialog_clear_cache_layout)
                                        .setCancelable(true)
                                        .create();

                                TextView title = dialog.findViewById(R.id.tv_title);

                                title.setText("温馨提示");

                                TextView content = dialog.findViewById(R.id.tv_content);
                                content.setText(giftResultBean.getMsg() + "");

                                //充值
                                TextView sure = dialog.findViewById(R.id.tv_sure);
                                sure.setText("充值");
                                sure.setOnClickListener(v -> {
                                    Intent it = new Intent(getActivity(), RechargeActivity.class);
                                    getActivity().startActivity(it);
                                    dialog.dismiss();

                                });

                                //取消
                                TextView cancel = dialog.findViewById(R.id.tv_cancel);
                                cancel.setText("取消");
                                cancel.setOnClickListener(v -> {
                                    dialog.dismiss();
                                });
                                dialog.show();
                                return;
                            }

                            MainPersonalModel.getPersonalDate(Constant.getLbsUserToken(), new ApiModel.CommonCallback<MyPersonalBean>() {
                                @Override
                                public void onSuccess(MyPersonalBean myPersonalBean) {
                                    Hawk.put(SPKey.SP_KEY_USER_MY_INFO, myPersonalBean);

                                }

                                @Override
                                public void onError(String errMsg) {

                                }
                            });


                            if (giveListBottomSheetDialogFragmentInterface != null) {
                                giveListBottomSheetDialogFragmentInterface.gift(money);
                            }
                            CostumerDialog dialog = new CostumerDialog.Builder(getContext(), R.style.custom_dialog_no_match)
                                    .setContentView(R.layout.dialog_send_gift_layout)
                                    .setCancelable(true)
                                    .create();
                            ImageView imageView = dialog.findViewById(R.id.tv_img);
                            TextView title = dialog.findViewById(R.id.tv_title);
                            title.setText("送给" + name + "一个" + PresentName);
                            GlideHelper.setLoadCirlcleImage(getActivity(), img, R.color.gray, imageView);
                            TextView min = dialog.findViewById(R.id.tv_minuse);
                            min.setText("-" + money + "蜜豆");
                            new Handler().postDelayed(() -> {
                                dialog.dismiss();
                                positionSelected = -1;
                                initViews();
                            }, 2000);
                            dialog.show();
                        }

                        @Override
                        public void onError(String errMsg) {
                            if (giveListBottomSheetDialogFragmentInterface != null) {
                                giveListBottomSheetDialogFragmentInterface.giftShowDialog(false);
                            }
                            ToastUtils.showShort(errMsg + "");
                        }
                    });
                } else {
                    CostumerDialog dialog = new CostumerDialog.Builder(getActivity(), R.style.custom_dialog_no_match)
                            .setContentView(R.layout.dialog_clear_cache_layout)
                            .setCancelable(true)
                            .create();

                    TextView title = dialog.findViewById(R.id.tv_title);

                    title.setText("温馨提示");

                    TextView content = dialog.findViewById(R.id.tv_content);
                    content.setText("当前余额不足，充值后可继续送礼，是否去充值？");

                    //充值
                    TextView sure = dialog.findViewById(R.id.tv_sure);
                    sure.setText("充值");
                    sure.setOnClickListener(v -> {
                        Intent it = new Intent(getActivity(), RechargeActivity.class);
                        getActivity().startActivity(it);
                        dialog.dismiss();

                    });

                    //取消
                    TextView cancel = dialog.findViewById(R.id.tv_cancel);
                    cancel.setText("取消");
                    cancel.setOnClickListener(v -> {
                        dialog.dismiss();
                    });
                    dialog.show();
                }
            }

            @Override
            public void onError(String errMsg) {

            }
        });

    }

    GiveListBottomSheetDialogFragmentInterface giveListBottomSheetDialogFragmentInterface;

    public void setGiveListBottomSheetDialogFragmentInterface(GiveListBottomSheetDialogFragmentInterface giveListBottomSheetDialogFragmentInterface) {
        this.giveListBottomSheetDialogFragmentInterface = giveListBottomSheetDialogFragmentInterface;
    }

    public interface GiveListBottomSheetDialogFragmentInterface {
        void gift(double price);

        void giftShowDialog(boolean show);
    }

}
